#include "DoublyLinkedList.h"
#include <stdio.h>
#include <stdlib.h>


//创建一个空链表
DList * create_list()
{
    //1.创建一个头结点，并初始化 
    DList * list = (DList *)malloc( sizeof(DList) );
    list->first = NULL;
    list->last = NULL;
    list->num = 0;

    //将头结点返回
    return list;
}


//往链表中插入一个元素
DList * insert_node( DList * list, DNode * pnew )
{
    if( list == NULL )
    {
        return NULL;
    }

    //插入操作
    if( list->first == NULL )       //从无到有
    {
        list->first = pnew;
        list->last = pnew;
    }
    else        //从少到多
    {
        //尾插法 
        list->last->next = pnew;
        pnew->prev = list->last;
        list->last = pnew;
    }
    //元素个数+1
    list->num++;

    return list;
}


//打印链表 
void print_list( DList * list )
{
    if( list == NULL )
    {
        return;
    }

    DNode * p = list->first;        //遍历指针
    while( p )
    {
        printf("%s ", p->data );
        p = p->next;        //往下一个走
    }
    putchar('\n');

    //测试：倒过来打印一遍
        p = list->last;
        while( p )
        {
            printf("%s ", p->data );
            p = p->prev;        //往前一个走
        }
        putchar('\n');

    printf("num = %d\n\n", list->num );
}

//销毁一条双向链表    
void destroy_list( DList * list )
{
    if( list == NULL )  //链表不存在
    {
        return ;
    }

    //1.遍历 先释放每一个数据节点 
    DNode * p = list->first;        //遍历指针

    while( p )
    {
        list->first = list->first->next;
        p->next = NULL;
        if( list->first != NULL )   //考虑只有一个节点，那么first往后走就为NULL
        {
            list->first->prev = NULL;
        }

        free( p );

        p = list->first;        //继续找下一个
    }

    //2.最后释放头结点
    list->first = NULL;
    list->last = NULL;
    list->num = 0;
    free( list );
}
